import tinycolor from 'tinycolor2';
import React from 'react';
import { toJS } from 'mobx';
import { Tools, Bubble, ActivityIndicator, Result, Icon, Modal } from 'weaver-mobile';
import {Form} from 'weaver-mobile-page';
const getLabel = Tools.getLabel;

export function regEmail(email) {
  let reg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
  let flag = true;
  if (email.indexOf(',') > -1) {
    email.split(',').forEach(v => {
      if (!reg.test(v)) flag = false;
    })
  } else {
    if (!reg.test(email)) flag = false;
  }
  return flag;
}

export function searchToQuery(search) {
  if (typeof search !== 'string') return {};
  search = decodeURI(search);
  const query = {};
  const reg = /[?&][^?&]+=[^?&]+/g;
  const arr = search.match(reg);
  if (Array.isArray(arr)) {
    arr.forEach(a => {
      const b = a.replace(/\?|&/g, '');
      const c = b.split('=');
      if (c.length === 2) {
        query[c[0]] = c[1];
      }
    });
  }
  return query;
}

export function getFontColorFromBgHex(hex) {
  const color = tinycolor(hex).getBrightness();
  return color < 127 ? '#fff' : '#000';
}

export const doConfirm = (title, msg, callback) => {
  return Modal.alert(title, msg, [
    { text: getLabel(201, '取消') },
    { text: getLabel(826, '确定'), onPress: () => {
      if (callback) callback();
    }},
  ]);
}

// 公共工具类
export const EmailConstant = {
	// 请求api请求错误统一处理方法
  catchApiError: (result) => {
    return new Promise((resolve, reject) => {
      if (result.status !== '1') {
        Bubble.error(result.msg || '接口调用失败！');
        reject(result);
        return;
      }
      resolve(result);
    });
  },
  // 操作api请求错误统一处理方法
  catchPostApiError: (result, msg) => {
    return new Promise((resolve, reject) => {
      if (result.status !== '1') {
        Bubble.error(result.msg || getLabel(83912, '操作失败！'));
        reject(result);
        return;
      }
      resolve(result);
    });
  },
}

export const renderLoading = (
  <div className="email-loading">
    <ActivityIndicator text="loading..." size="large" />
  </div>
);

export const renderNoData = (
  <div className="email-nodata">
    <Result
      img={<Icon type="no-data" />}
      message={getLabel(83553, '暂无数据')}
    />
  </div>
)

export const getFields = (form, conditions) => {
  let { conditioninfo, isInit } = form;
  conditioninfo = conditions || toJS(conditioninfo);
  const fields = [];
  if (isInit) {
    conditioninfo.forEach((group) => {
      group.items.forEach((field) => {
        if (typeof(field.hide) === 'boolean' && field.hide) {
          return;
        }
        if (typeof(field.hide) === 'function') {
          if (field.hide(toJS(form.formData), field)) {
            return;
          }
        }
        fields.push(<Form.Item
          key={field.domkey.join('__')}
          form={form}
          fieldConfig={field}
          onChange={(...args) => {
            if (field.onChange) {
              const onChangeValue = field.onChange(...args);
              if (onChangeValue instanceof Promise) {
                onChangeValue.then(() => {
                  form.onChange.apply(this, args);
                });
              } else {
                form.onChange.apply(this, args);
              }
            }
          }}
          itemProps={field.itemProps}
          children={field.otherCom}
        />);
      });
    });
  }
  return fields;
}

export const shadowEqual = (value, other) => {
  if (typeof(value) !== 'object') return value === other;
  else if (typeof(value) !== typeof(other)) return false;
  else if (Object.keys(value).length !== Object.keys(other).length) return false;
  for (let key in value) {
    if (value[key] !== other[key]) return false;
  }
  return true;
}

// 十六进制颜色转rgb
export function colorRgb(colorStr) {
  const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  let sColor = colorStr.toLowerCase();
	if(sColor && reg.test(sColor)){
		if(sColor.length === 4){
			let sColorNew = '#';
			for(let i = 1; i < 4; i += 1){
				sColorNew += sColor.slice(i, i+1).concat(sColor.slice(i, i+1));	
			}
			sColor = sColorNew;
		}
		//处理六位的颜色值
		const sColorChange = [];
		for(let i = 1; i < 7; i += 2){
			sColorChange.push(parseInt(`0x${sColor.slice(i, i+2)}`, 16));
		}
		return sColorChange;
	}else{
		return sColor;
	}
};

export function closest(el, selector) {
  const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
  while (el) {
    if (matchesSelector.call(el, selector)) {
      return el;
    }
    el = el.parentElement;
  }
  return null;
}

// 遍历condition
export function loopCondition(condition, cb = () => {}) {
  if (Array.isArray(toJS(condition)) && condition.length > 0) {
    const loop = (conditioninfo) => {
      return conditioninfo.map(cb);
    };
    if (Array.isArray(toJS(condition[0].items))) {
      return condition.map((conditions) => ({ ...conditions, items: loop(conditions.items) }));
    } else {
      return loop(condition);
    }
  }
}

//判断是否是否支持EM接口
const judgeApiSupport = (apiname) => {
  return !!window.em;
}

export const TitleUtil = {
  // 控制EM客户端顶部头信息
  setTitle: (title) => {
    document.title = title ? title : "" ;//和飞信中走此段,和飞信不进下面if语句
    window.document.title = title ? title : getLabel(71,'邮件');
    if (!judgeApiSupport("configNavigation")){
      return;
    }
    const nav = {
      'success': function (argument) {
          console.log('controlEmTopNav success', JSON.stringify(argument));
      },
      'fail': function (argument) {
          console.log('controlEmTopNav fail', JSON.stringify(argument));
      },
      'left': {},
      'right': {},
      'title': '',
      showCloseButton: true
    };
   
    window.em.ready(function(){
      if(title===undefined){
        title = "" || getLabel(71,'邮件');
      }
      window.em.configNavigation({...nav, title });//微信中走此段
    });
  },
  //重置EM表单的头
  resetEmElement: () => {
    if (judgeApiSupport("resetNavigation")) {
      window.em.ready(function(){
        window.em.resetNavigation({title: ''});
      });
    }
  }
};

export const compareParams = (propA = {}, propB = {}) => {
  let flag = true;
  // 如果需要把A对象拆分，需要该方法 -- 重塑A对象
  for (let a in propA) {
    if (a.includes('__')) {
      let splitItem = a.split("__");
      if (splitItem.length > 0) {
        splitItem.map(item => {
          if (!propA[item]) propA[item] = propA[a]
        })
      }
    }
  }

  for (let b in propB) {
    if (propA[b] || propA[b] === '' || propA[b] === 0) {
      if (propB[b] !== propA[b]) {
        flag = false;
        break
      }
    }
  }

  return flag;
}

export const isHighlight = function (store) {
  let islight = false;
  if (store) {
    const { formData, defaultValues } = store.form;
    if (JSON.stringify(formData) !== JSON.stringify(defaultValues)) {
      islight = true;
    }
  }
  return islight;
}